
using PetShop.Web.Controls;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Petshop.Backend.Data;
using PetShop.Web.Entities;

namespace PetShop.Web {
	public class EditAccount : Page {
	
		protected Label lblUserId;
		protected TextBox txtEmail;
		protected AddressUI addr;
		protected NavBar header;
		protected System.Web.UI.WebControls.RequiredFieldValidator valEmail;
		protected System.Web.UI.WebControls.ImageButton btnSubmit;
		protected System.Web.UI.HtmlControls.HtmlForm frmEditAcct;
		protected Preferences prefs;
		
		override protected void OnLoad(EventArgs e) {
			if (!IsPostBack) {

				ProcessFlow.AccountController accountController = new ProcessFlow.AccountController();

				// Retrieve the account information from the account controller
				Account myAccount = accountController.GetAccountInfo(true);
				
				lblUserId.Text = myAccount.UserId;
				txtEmail.Text = myAccount.Email;
                addr.Address = new AddressInfo() { Address1 = myAccount.Addr1, Address2 = myAccount.Addr2, City = myAccount.City, Country = myAccount.Country, FirstName = myAccount.FirstName, LastName = myAccount.LastName, Phone = myAccount.Phone, State = myAccount.State, Zip = myAccount.Zip };
				prefs.Language = myAccount.LangPref;
				prefs.Category = myAccount.FavCategory;
				prefs.IsShowBanners = myAccount.BannerOpt.HasValue && myAccount.BannerOpt.Value==1?true:false;
                prefs.IsShowFavorites = myAccount.MyListOpt.HasValue && myAccount.MyListOpt.Value == 1 ? true : false;				
			}
		}

		private void InitializeComponent() {
		}

		protected void SubmitClicked(object sender, ImageClickEventArgs e) {
			if (Page.IsValid) {

				ProcessFlow.AccountController accountController = new ProcessFlow.AccountController();

				// Retrieve the account information from the account controller
				Account myAccount = accountController.GetAccountInfo(true);

				// Merge in the changes
				string email = WebComponents.CleanString.InputText(txtEmail.Text, 50);
				AddressInfo address = addr.Address;
				string language = prefs.Language;
				string favCategory = prefs.Category;
				bool showFavorites = prefs.IsShowFavorites;
				bool showBanners = prefs.IsShowBanners;

                Account updatedAccountInfo = new Account() { UserId = myAccount.UserId, Password = myAccount.Password, Email = email, Addr1= address.Address1 , Addr2 = address.Address2, City = address.City, Country = address.Country, FirstName = address.FirstName, LastName = address.LastName, Phone = address.Phone, State = address.State, Zip = address.Zip,  BannerOpt=(showBanners?1:0) , MyListOpt =(showFavorites?1:0),LangPref = language, FavCategory = favCategory };

				// Submit the changes back to the controller
				accountController.UpdateAccount(updatedAccountInfo);
			}
		}
	}
}